package com.haoze.common.utils;



import com.haoze.common.dto.UserEntity;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Chenchao
 * @CreateTime: 2019-07-20 08:31
 */
public class Contrast {

    //记录每个修改字段的分隔符
    public static final String separator = ";";

    /**
     * 比较两个对象,并返回不一致的信息
     *pojo1:old  pojo2:new
     */
    public static Map<String,Map> contrastObj(Object pojo1, Object pojo2) {
        Map<String,Map> result = new HashMap();
        try {
            Class clazz = pojo1.getClass();
            Field[] fields = pojo1.getClass().getDeclaredFields();
            int i = 1;
            for (Field field : fields) {
                if ("serialVersionUID".equals(field.getName())) {
                    continue;
                }
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                Method getMethod = pd.getReadMethod();
                Object o1 = getMethod.invoke(pojo1);
                Object o2 = getMethod.invoke(pojo2);
                if (o1 == null || o2 == null) {
                    continue;
                }
                if (o1 instanceof Date) {
                    o1 = formatDate((Date) o1);
                }
                if (!o1.toString().equals(o2.toString())) {
                    Map<String,Object> temp=new HashMap();
                    temp.put("old",o1);
                    temp.put("new",o2);
                    result.put(field.getName(),temp);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String formatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return null == date ? null : sdf.format(date);
    }


}
